# 线性回归练习1
# In[]
# 根据学生的学习时长，预测其成绩
import numpy as np 
import matplotlib.pyplot as plt 
from sklearn.linear_model import LinearRegression,HuberRegressor
from sklearn.preprocessing import StandardScaler 
import seaborn as sns

X = np.array([6,7,7.5,8,6.6,8.1,6.8,6.9,7.3,6.9]).reshape(-1,1)
y = np.array([53,60,56,79,58,85,70,56,69,76])

lr = LinearRegression()
hr = HuberRegressor()
lr.fit(X,y)
hr.fit(X,y)
# 画散点图
plt.scatter(X,y,marker='o',c='r',s=10)
x = [[X.min()],[X.max()]]
y_lr = lr.predict(x)
y_hr = hr.predict(x)
plt.xlabel('learning-time')
plt.ylabel('score')
# lr曲线
plt.plot(x,y_lr,label='lr')
# Hr曲线
plt.plot(x,y_hr,label='hr')

# 预测
y_hat_lr = lr.predict(np.array([[7.2]]))
y_hat_hr = hr.predict(np.array([[7.2]]))
plt.scatter([7.2],[y_hat_lr],label='lr_pre=%.1f'%(y_hat_lr),marker='x',s=100)
plt.scatter([7.2],[y_hat_hr],label='hr_pre=%.1f'%(y_hat_hr),marker='x',s=100)
plt.legend()
plt.show()


# 根据汽车的使用年限，预测二手车的价格
#%%
import numpy as np 
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
X = np.array([4,4,5,5,7,7,8,9,10,11]).reshape(-1,1)
y = np.array([6300,5800,5700,4500,4500,4200,4100,3100,2100,2500])

lr = LinearRegression()
lr.fit(X,y)
print('汽车使用年限与其价格成:',('正相关' if lr.coef_[0] > 0 else '负相关'))

plt.scatter(X,y,s=10)
plt.xlim(3,13)
x_line = [[X.min()],[X.max()]]
y_line = lr.predict(x_line)
plt.xlabel('years')
plt.ylabel('price')
plt.plot(x_line,y_line)
y_pred = lr.predict(np.array([[12]]))

plt.scatter([12],y_pred,marker='x',s=100,label='predic:%.0f'%(y_pred))
plt.legend()
plt.show()


#%%
